import { showSuccessToast, showFailToast } from "vant";
// 获取环境变量
export const getEnvValue = (type: string) => {
  return import.meta.env[type]
}

// 获取url中参数
export const getQueryString = (url: string, queryKey: string) => {
  const reg = new RegExp(`&{1}${queryKey}\\=[a-zA-Z0-9_-]+`, 'g')
  const matchResult = url.replace(/\?/g, '&').match(reg)![0]
  return matchResult.substr(matchResult.indexOf('=') + 1)
}

// 锚点
export const anchor = (scrollDom, topDom, moveDom, type = 'add', num = 0) => {
  let one = Math.floor(moveDom.getBoundingClientRect().top)
  let two = Math.floor(topDom.getBoundingClientRect().top);
  if (two === num) {
    return
  } else {
    if (type === 'add') {
      let tree = (one + Math.abs(two)) + num
      scrollDom.scrollTop = tree;
    } else {
      let tree = (one + Math.abs(two)) - num
      scrollDom.scrollTop = tree;
    }
  }
}
/**
 * 复制文本
 * @param text 文本 
 */
export const copyTextToClipboard = (text) => {
  // 创建一个临时的文本输入框  
  var textArea = document.createElement("textarea");
  textArea.style.position = "fixed";
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.width = "2em";
  textArea.style.height = "2em";
  textArea.style.padding = "0";
  textArea.style.border = "none";
  textArea.style.outline = "none";
  textArea.style.boxShadow = "none";
  textArea.style.background = "transparent";
  textArea.value = text;

  // 将文本输入框添加到文档中  
  document.body.appendChild(textArea);

  // 选中并复制文本  
  textArea.focus();
  textArea.select();

  try {
    // 尝试使用 execCommand 来复制文本  
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    if (successful) {
      showSuccessToast({ type: 'success', message: '复制成功' });
    } else {
      showFailToast('复制失败')
    }
  } catch (err) {
    showFailToast('复制失败')
  }

  // 从文档中移除文本输入框  
  document.body.removeChild(textArea);
}

// 根据特定的条件去将树结构中不符合条件的数据清除
export const removeInvalidNodes = (treeData: any, field: string) => {
  return treeData.filter((node: any) => node[field] === 0).map((node: any) => ({ ...node, children: node.children ? removeInvalidNodes(node.children, field) : [] }));
}

// 文本标签去除标签
export const stripTags = (str: string) => {
  return str.replace(/<\/?[^>]+(>|$)/g, '');
}

/** 取最后一个非空字符串 */
export const getLastNonEmptyValue = (arr) => {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] &&arr[i] !== '') {
      return arr[i];
    }
  }
  return null;
}

/** 取最后一个非空数组 */
export const getLastNonEmptyList = (arr) => {
  for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] && arr[i].id !== '') {
      return arr[i];
    }
  }
  return null;
}